package org.example.chapter1;

import org.example.util.Util;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * 编写 lua 脚本，将多个redis命令变为一个原子操作
 */
public class HW1_4_8_LuaScripting {
    public static void main(String[] args) {
        Object o = testLuaScripting(getScript1());
        System.out.println(o);
    }

    public static Object testLuaScripting(String script) {
        Jedis jedis = Util.getJedis();
        List<String> keys = List.of("key2");
        List<String> argvs = List.of("0", "inf", "limit", "0", "1");
        return jedis.eval(script, keys, argvs);
    }

    public static String getScript1() {
        return "local s = redis.call('zrangebyscore', KEYS[1], ARGV[1], ARGV[2], ARGV[3], ARGV[4], ARGV[5]) "
                + " if(type(s) == nil or #s == 0) then " +
                " return 0 "
                + " else local res = redis.call('zrem', KEYS[1], s[1]) end"
                + " return 1 ";
    }
}
